package homework.xuluoxi;

/*
 * 作业名称：TCP模型
 * 作业功能：实现客户端与服务器之间的模拟登录
 * 分　　类：客户端
 * 学　　员：徐罗希
 * 版　　本：V1.0
 * 备　　注：模块四作业
 */

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {

    // 定义私有成员变量
    private Socket socket = null;

    public static void main(String[] args) {

        // 连接服务器
        Client myClient = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            myClient = new Client();
            myClient.socket = new Socket("127.0.0.1", 3333);
            System.out.println("已成功连接服务器");

            // 向服务器发送用户名、密码信息
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入用户名：");
            String userName = scanner.next();
            System.out.print("请输入密码：");
            String passWord = scanner.next();
            scanner.close();
            oos = new ObjectOutputStream(myClient.socket.getOutputStream());
            oos.writeObject(new UserMessage("Ready", new User(userName, passWord)));
            System.out.println("数据已成功发送服务器");

            // 接收服务器回传的结果
            ois = new ObjectInputStream(myClient.socket.getInputStream());
            UserMessage userMessage = (UserMessage) ois.readObject();
            System.out.println("服务器回传结果接收成功");

            // 判断最后结果
            System.out.println("Success".equals(userMessage.getType()) ? "登录成功" : "登录失败");
        }
        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            try {
                ois.close();
                oos.close();
                myClient.socket.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
